<?php
/**
 * Created by PhpStorm.
 * User: hengsu
 * Date: 2016/5/30
 * Time: 10:59
 */

namespace Home\Controller;
use Think\Controller;

class PayController extends Controller{
    static $orderPayUrl='https://api.mch.weixin.qq.com/pay/unifiedorder';
    /**
     * @param $orderId
     * @param $body
     * @param $total
     * @param $type
     * @param $openid
     * @return array|bool
     */
    static public function wechatPay($orderId,$body,$total,$type='',$openid=''){
        $data=array(
            'appid'           =>          C('APPID'),
            'mch_id'          =>          C('MCH_ID'),
            'nonce_str'       =>          time(),
            'body'            =>          $body,
            'out_trade_no'    =>          $orderId,
            'total_fee'       =>          $total*100,
            'spbill_create_ip'=>          user_ip(),
            'notify_url'      =>          C('WECHAT_URL').'/type/'.$type,
            'trade_type'      =>          'JSAPI'
        );
        if($openid != '') {
            $data['openid'] = $openid;
        }
        $data['sign']         =           PayController::getSignature($data,'md5');
        //$payObj=json_decode(json_encode($data),true);
        $xmlstr=PayController::wechatOrderXML($data);
        //var_dump($data);exit;
        $request=PayController::https_request(PayController::$orderPayUrl,$xmlstr);
		//var_dump($request);exit;
        $postObj = simplexml_load_string($request, 'SimpleXMLElement', LIBXML_NOCDATA);
        if ($postObj->return_code == 'SUCCESS' && $postObj->result_code == 'SUCCESS' ){
            return PayController::wechatJsApi($postObj->prepay_id);
        }else{
            return false;
        }
    }
    /**
     * @param $orderId
     * @param $body
     * @param $total
     * @param $type
     * @param $openid
     * @return array|bool
     */
    static public function wechatWapPay($orderId,$body,$total,$type=''){
        $data=array(
            'appid'           =>          C('APPID'),
            'mch_id'          =>          C('MCH_ID'),
            'nonce_str'       =>          time(),
            'body'            =>          $body,
            'out_trade_no'    =>          $orderId,
            'total_fee'       =>          (int)$total*100,
            'spbill_create_ip'=>          user_ip(),
            'notify_url'      =>          C('WECHAT_URL').'/type/'.$type,
            'trade_type'      =>          'WAP'
        );
        $data['sign']         =           PayController::getSignature($data,'md5');
        $payObj=json_decode(json_encode($data),true);
        $xmlstr=PayController::wechatOrderXML($payObj);
        //var_dump($xmlstr);exit;
        $request=PayController::https_request(PayController::$orderPayUrl,$xmlstr);
        var_dump($request);exit;
        $postObj = simplexml_load_string($request, 'SimpleXMLElement', LIBXML_NOCDATA);
        if ($postObj->return_code == 'SUCCESS' && $postObj->result_code == 'SUCCESS' ){
            return PayController::wechatJsApi($postObj->prepay_id);
        }else{
            return false;
        }
    }
    /**
     * @param $prepay_id
     * @return array
     */
    static private function wechatJsApi($prepay_id){
        $data=array(
            'appId'           =>          C('APPID'),
            'timeStamp'       =>          time(),
            'nonceStr'        =>          MD5(time()),
            'package'         =>          'prepay_id='.$prepay_id,
            'signType'        =>          'MD5',
        );
        $data['paySign']=PayController::getSignature($data,'MD5');
        return $data;
    }
    /**
     * 获取签名
     * @param array $arrdata 签名数组
     * @param string $method 签名方法
     * @return boolean|string 签名值
     */
    static private function getSignature($arrdata,$method="sha1") {
        if (!function_exists($method)) return false;
        ksort($arrdata);
        $paramstring = "";
        foreach($arrdata as $key => $value)
        {   if($value != null){
                if(strlen($paramstring) == 0)
                    $paramstring .= $key . "=" . $value;
                else
                    $paramstring .= "&" . $key . "=" . $value;
            }

        }
        $paramstring=$paramstring.'&key='.C('WECHAT_KEY');
        $Sign = $method($paramstring);
        $Sign = strtoupper($Sign);
        return $Sign;
    }

    /**
     * @param object $object   生成xml的对象
     * @return string
     */
    static private function wechatOrderXML($object){
        $xmlstr='<xml>';
        foreach ($object as $key => $val){
            $xmlstr.="<$key>$val</$key>";
        }
        $xmlstr.='</xml>';

        return $xmlstr;
    }

    /**
     * @param $url  请求路径
     * @param null $data   请求参数
     * @return mixed
     */
    private function https_request($url,$data = null){
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        if (!empty($data)){
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        }
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($curl);
        curl_close($curl);
        return $output;
    }
    
}